'use strict';

const semver = require('semver')
const colors = require('colors'); 
const log = require('@xqc-ink-cli/log');
const LOWEST_NODE_VERSION = '16.0.0'

class Command {
    constructor(argv) { 
        if(!argv){
            throw new Error(colors.red(`Command init 参数不能为空`))
        }
        if(!Array.isArray(argv)){
            throw new Error(colors.red(`Command init 参数必须为数组`))
        }
        if(argv.length < 1){
            throw new Error(colors.red(`Command init 参数数组不能为空`))
        }
        this._argv = argv;
        let runner = new Promise((resolve, reject) => {
            let chain = Promise.resolve()
            chain = chain.then(_ => this.checkNodeVersion())
            chain = chain.then(_ => this.initArgs())
            chain = chain.then(_ => this.init())
            chain = chain.then(_ => this.exec())
            chain.catch(err => {
                log.error(err.message);
            })
        })
    }
    initArgs(){
        this._cmd = this._argv[this._argv.length - 1] || {}
        this._argv = this._argv.slice(0, this._argv.length - 1)
        // for (const key in this._cmd._optionValues) {
        //     this._cmd[key] =  this._cmd._optionValues[key]
        // } 
        this._optionValues = this._cmd._optionValues || {}
    }
    /**
     *  1. 获取当前node版本号
     *  2. 最低版本号
     *  3. 通过semver版本比对库
     *  4. Promise捕获异常
     *  5. @xqc-ink-cli/log 打印异常
     */
    checkNodeVersion(){ 
        const currentVersion = process.version
        const lowestNodeVersion = LOWEST_NODE_VERSION
        if(!semver.gte(currentVersion, lowestNodeVersion)) {
            throw new Error(colors.red(`xqc-ink-cli 需要安装 v${lowestNodeVersion} 版本以上的node.js`))
        }
    }

    init(){
        throw new Error('init 必须实现')
    }

    exec(){
        throw new Error('exec 必须实现')
    }
}
module.exports = Command;